
const app = getApp()
const WXAPI = require('../../api/api')
Page({
  data: {
    paymentApi: "贵司后端接口-获取支付信息，数据返回格式请参考：https://docs.qq.com/doc/DTVdaWUVLTWx4Q01v 接口文档：2、获取支付信息",
    openid: "用户openid",//请根据实际情况获取
    source: app.globalData.source,
	  orderUrl:"" //用户付款完成后跳转的订单url
  },
  onLoad(e) {
    
    wx.showToast({
      title: '哈哈哈哈',
    })
    
	 // 订单编号
   console.log(e.orderId)
   console.log(e.orderUrl)
   this.setData({
   	   orderUrl:e.orderUrl
   })
   //获取支付信息请求
	 this.getpayInfo(e.orderId)
  },
  getCode() {
    // 登录 
    let that = this;
    return new Promise((resolve,reject) => {
      wx.login({
        success: function (res) {
          if (res.code) {
            resolve(res.code)
            console.log('获取code', res.code)
          } else {
            reject()
            console.log('获取code失败', res.errMsg)
          }
        }
      })
    })
  },
  // 使用订单号获取支付信息
  async getpayInfo(orderId){
    var appId = app.globalData.appid
    var code = await this.getCode()
    let data = {
      orderNo:orderId,
      code: code,
      appId: appId,
    }
    WXAPI.jtkPay(data, res => {
      if(res.code == 200){
        this.payMoney(res.result.wxpay)
      }else{
        wx.showToast({
          title: res.msg,
          icon:'none'
        })
      }
    });
  },
  // 付款
  payMoney(data){
      wx.requestPayment({
        timeStamp: data.timeStamp,
        nonceStr: data.nonceStr,
        package: data.package,
        signType: data.signType,
        paySign: data.paySign,
        success: () => {
          //支付成功
          wx.navigateTo({
            url:"/pages/openwebview/openwebview?url=" + this.data.orderUrl
          })
        },
        fail: (res) => { 
          //支付失败
          wx.showToast({
            title:'支付失败',
            icon:'none'
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 1500);
        }
    })
  }
})
